﻿namespace BEGDC.CC.Web.UserControls.CR
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Collections;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using BEGDC.CC.BL.CCFlow.CR;
    using BEGDC.CC.BL.CCFlow.CV;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.Common.Query;
    using BEGDC.CC.BL.Workflow;
    using BEGDC.CC.BL.Common;
    using BEGDC.Utility.Castle;
    using BEGDC.CC.BL.UserManagement;

    /// <summary>
    ///		Summary description for NormalRequest.
    /// </summary>
    public class NormalRequest : BaseCR
    {
        //Button 
        protected System.Web.UI.WebControls.Button ibtnSubmit;
        protected System.Web.UI.WebControls.Button ibtnSave;
        protected System.Web.UI.WebControls.Button ibtnReply;
        protected System.Web.UI.WebControls.Button ibtnCopy;
        //CR.PrintCtrl
        protected BEGDC.CC.Web.UserControls.CR.PrintCtrl PrintCtrl;
        //StampCtrl
        protected BEGDC.CC.Web.Common.StampCtrl StampCtrl;
        //Export
        protected BEGDC.CC.Web.UserControls.Export ctrlExport;
        //EZCtrl - 由COD转账(去掉)
        //protected BEGDC.CC.Web.UserControls.CR.EZCtrl EZCtrl;
        //NormalCtrl-自己现金核销或客户自理
        protected BEGDC.CC.Web.UserControls.CR.NormalCtrl NormalCtrl;
        //TextBox
        protected System.Web.UI.WebControls.TextBox tbOperationFlag1;
        protected System.Web.UI.WebControls.TextBox Ctl_hiddenDept;
        protected System.Web.UI.WebControls.TextBox Ctl_hiddenBranch;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        //Label
        protected System.Web.UI.WebControls.Label lbAppNo;

        //protected string _Branch = "";

        //HtmlControls
        protected System.Web.UI.HtmlControls.HtmlInputHidden hiddenScrollHight;
        protected System.Web.UI.HtmlControls.HtmlTableRow TR_title;

        //protected System.Web.UI.WebControls.Label tx_AppState;
        //protected System.Web.UI.HtmlControls.HtmlGenericControl SampleEZ;
        //protected System.Web.UI.HtmlControls.HtmlGenericControl SampleNormal;

        #region BoolValues

        protected bool _Transition = false;
        bool saveBeforeSubmit = false;//joan 2008/8/22
        bool isReadOnly = false;

        private bool IsQuery
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                return state == SysDicItem.ProjectStatusFlag.QUERY;
            }
        }

        private bool IsView
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                if (state == SysDicItem.ProjectStatusFlag.View || state == SysDicItem.ProjectStatusFlag.CANCEL
                    || state == SysDicItem.ProjectStatusFlag.Pending || state == SysDicItem.ProjectStatusFlag.End
                    || state == SysDicItem.ProjectStatusFlag.Participation)
                    return true;
                else
                    return false;
            }
        }
        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return WorkTransition.Draft;
                else
                    return flowInstance.CurrentActiveStep.StepCode;
            }
        }

        #endregion

        #region Form Properties
        protected string Department
        {
            get { return (string)this.ViewState["Department"]; }
            set { this.ViewState["Department"] = value; }
        }
        protected string Branch
        {
            get { return (string)this.ViewState["Branch"]; }
            set { this.ViewState["Branch"] = value; }
        }
        protected bool Transition
        {
            get
            {
                string TranStr = (string)this.ViewState["Transition"];
                if (TranStr == "1")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            set
            {
                if (value)
                {
                    this.ViewState["Transition"] = "1";
                }
                else
                {
                    this.ViewState["Transition"] = "0";
                }
            }
        }
        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            if (!this.IsPostBack)
            {
                ////John Add 8/12
                InValidAllSession();

                //Session[SessionFlag.AccompanySession] = null;
                //Session[SessionFlag.CustomerSession] = null;
                //Session[SessionFlag.AccompanySessionEZ] = null;
                //Session[SessionFlag.CustomerSessionEZ] = null;

                Session[SessionFlag.CompanyCarSession] = null;
                Session[SessionFlag.CompanyCarSessionEZ] = null;
                Session[SessionFlag.LeaseCarSession] = null;
                Session[SessionFlag.LeaseCarSessionEZ] = null;
                Session[SessionFlag.HotelSession] = null;
                Session[SessionFlag.HotelSessionEZ] = null;

                Session[SessionFlag.ContractInfo] = null;
                Session[SessionFlag.CostCenter] = null;
                base.PreInitForm();

                BuildFormProperties();

                this.ibtnCopy.Attributes["onclick"] = "javascript:OnCopy();";
                this.ibtnSubmit.Attributes["onclick"] = "javascript:OpenAssignmentPane(" + this.AppID + ",'" + this.Transition + "');";
                this.ibtnReply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["FlowID"] + ");");

                ButtonStatusSetting();

                InitForm();

                //Check Access
                //Accessibility access = this.CheckAccessibility(WorkTransition.CR_Request, BEGDC.CC.BL.Workflow.UserRole.CRApplicant);
                //ControlStatusSetting( access );

                if (this.IsView)
                {
                    this.TR_title.Visible = false;
                }
            }
            //Page.SmartNavigation = true;
            //Page.RegisterOnSubmitStatement("AutoScroll_OnSubmit","return AutoScrollOnSubmit();");
        }

        //#region ControlStatusSetting
        //private void ControlStatusSetting(Accessibility access)
        //{
        //    if (access == Accessibility.Readonly)
        //    {
        //        this.DisableChildrenControls(this);
        //        //this.stampCtrl1.Visible = false;
        //    }
        //}
        //#endregion

        #region Build Form Properties
        private void BuildFormProperties()
        {
            IUser userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
            Employee CurrentRequestor = userService.GetUser(HttpContext.Current.User.Identity.Name);

            if (CurrentRequestor.Department != null)
            {
                this.Branch = CurrentRequestor.Department.Id.ToString();
                this.Ctl_hiddenBranch.Text = this.Branch;
                this.Department = CurrentRequestor.Department.DepartmentType.DicItemKey;
                this.Ctl_hiddenDept.Text = this.Department;
            }

            string TranStr = Request.QueryString["Transition"];

            if (TranStr != null && TranStr != "")
            {
                if (TranStr == "1")
                {
                    this.Transition = true;
                }
                else
                {
                    this.Transition = false;
                }
            }
        }
        #endregion

        #region InitForm
        private void InitForm()
        {
            long flowId = this.LoadApplication();

            if (this.Application != null)
            {
                if (this.Application.AppNo != string.Empty)
                    this.lbAppNo.Text = " Application No:" + this.Application.AppNo;

                //UPDATE FORM PROPERTIES IF IT IS QUERY BACK
                if (this.Application.DepartmentType != null)
                {
                    this.Department = this.Application.DepartmentType.DicItemKey;
                }
                if (this.Application.DepartmentName != null)
                {
                    this.Branch = this.Application.DepartmentName.Id.ToString();
                }
                this.Transition = this.Application.IsTransition;

                //Display Copy Button
                if (flowId == 0)
                {
                    this.ibtnCopy.Visible = true;
                    this.StampCtrl.Visible = false;
                }

                //Decide the application type whether EZ or normal
                // True - EZ  False - Normal
                if (!this.Transition)
                {
                    NormalCtrl.Visible = true;
                    NormalCtrl.isReadOnly = isReadOnly;
                    NormalCtrl.App = this.Application;
                }
            }
            else if (this.AppID == 0 && this.Application == null)
            {
                if (!this.Transition)
                {
                    NormalCtrl.Visible = true;
                    NormalCtrl.isReadOnly = false;
                    NormalCtrl.App = this.Application;
                }
                PrintCtrl.Visible = false;
                this.StampCtrl.Visible = false;
            }
            else
            {
                WebUtility.Go2ErrorPage(this.Page, "wrong Application ID");
            }
        }
        #endregion

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///Required method for Designer support - do not modify
        ///the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ibtnCopy.Click += new EventHandler(CopyBtn_Click);
            this.ibtnSubmit.Click += new EventHandler(SubmitBtn_Click);
            this.ibtnSave.Click += new EventHandler(SaveBtn_Click);
            this.ibtnReply.Click += new EventHandler(ReplyBtn_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }

        #endregion

        //#region BuildObjects

        //private DataTable BuildSessionTable(string SessionName)
        //{
        //    DataTable dataTable = null;
        //    object SessDataTable = Session[SessionName];
        //    if (SessDataTable != null)
        //    {
        //        dataTable = (DataTable)SessDataTable;
        //    }
        //    return dataTable;
        //}

        private IList BindFlowMember()
        {
            IList MemberList = new ArrayList();
            string[] Str = null;
            if (Session["CATDirector"] != null)
            {
                Str = new string[3];
                Str[0] = BEGDC.CC.BL.Workflow.UserRole.CATDirector;
                Str[1] = Session["CATDirector"].ToString();
                Str[2] = BEGDC.CC.BL.Workflow.WorkTransition.CR_CATDirectorApproval;
                MemberList.Add(Str);
            }
            if (Session["PSOHead"] != null)
            {
                Str = new string[3];
                Str[0] = BEGDC.CC.BL.Workflow.UserRole.PSO;
                Str[1] = Session["PSOHead"].ToString();
                Str[2] = BEGDC.CC.BL.Workflow.WorkTransition.CR_PSOHeadApproval;
                MemberList.Add(Str);
            }
            if (Session["DeptDirector"] != null)
            {
                Str = new string[3];
                Str[0] = BEGDC.CC.BL.Workflow.UserRole.DeptDirector;
                Str[1] = Session["DeptDirector"].ToString();
                Str[2] = BEGDC.CC.BL.Workflow.WorkTransition.CR_DeptDirectorApproval;
                MemberList.Add(Str);
            }

            Session["CATDirector"] = null;
            Session["PSOHead"] = null;
            Session["DeptDirector"] = null;

            return MemberList;
        }

        private void InValidAllSession()
        {
            Session[SessionFlag.CustomerSession] = null;
            Session[SessionFlag.AccompanySession] = null;
            Session[SessionFlag.HotelSession] = null;
            Session[SessionFlag.CompanyCarSession] = null;
            Session[SessionFlag.LeaseCarSession] = null;
            Session[SessionFlag.AccompanySessionEZ] = null;
            Session[SessionFlag.CustomerSessionEZ] = null;
            Session[SessionFlag.CompanyCarSessionEZ] = null;
            Session[SessionFlag.LeaseCarSessionEZ] = null;
            Session[SessionFlag.HotelSessionEZ] = null;
            Session[SessionFlag.ContractInfo] = null;
            Session[SessionFlag.CostCenter] = null;
            Session["CATDirector"] = null;
            Session["CATVP"] = null;
            Session["PSOHead"] = null;
            Session["DeptDirector"] = null;
            Session["DeptHead"] = null;
            Session["FNCController"] = null;
        }

        //#endregion

        #region Save
        void SaveBtn_Click(object sender, EventArgs e)
        {
            string url = Request.Form["tbURL"];
            string script = "<script>";
            try
            {
                //OBTAIN BASIC INFORMATION
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
                BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

                if (!this.Transition)
                {
                    App = NormalCtrl.BuildApplication(App);
                    if (App == null) return;
                    if (App.DepartmentType == null && this.Department != "")
                    {
                        App.DepartmentType = utility.GetDicItem(this.Department, BEGDC.CC.BL.Common.DicType.DepartmentType);
                        App.IsTransition = this.Transition;
                    }
                    if (App.DepartmentName == null && this.Branch != null && this.Branch != "")
                    {
                        App.DepartmentName = new Department();
                        App.DepartmentName.Id = Convert.ToInt32(this.Branch);
                    }

                    BEGDC.CC.Entity.CustomerInfo customerinfo = NormalCtrl.BuildCustomer(App);
                    BEGDC.CC.Entity.LogisticalInfo logisticinfo = NormalCtrl.BuildLogistic(App);
                    IList VisitingList = NormalCtrl.BuildAppVisiting();

                    //OBTAIN SESSION INFORMATION
                    DataTable CustomerTable = this.NormalCtrl.CustomerDataTable;
                    DataTable AccompanyTable = this.NormalCtrl.ALAttendeeDataTable;
                    DataTable HotelTable = this.NormalCtrl.HotelDataTable;
                    DataTable CompanyCarTable = this.NormalCtrl.CompanyCarDataTable;
                    DataTable LeaseCarTable = this.NormalCtrl.LeaseCarDataTable;

                    App.ApplicationType = WorkflowTypes.CR;
                    CRService.SaveNormalApplication(App, customerinfo, logisticinfo, VisitingList, CustomerTable, AccompanyTable, HotelTable, CompanyCarTable, LeaseCarTable, false);

                    this.AppID = App.Id;
                    this.Application = App;

                    Session["AppID"] = this.Application.Id;

                    if (url == string.Empty)
                        script += "alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');";
                    script += "var scollvalue = $('input.positionflag').val();";
                    if (url != string.Empty)
                    {
                        if (url.IndexOf("AppID") == -1)
                            url = url.Substring(0, url.IndexOf("?") + 1) + "AppID=" + this.Application.Id + "&" + url.Substring(url.IndexOf("?") + 1);
                        script += "window.location.href='" + url + "'";
                    }
                    else
                    {
                        url = Request.Url.AbsoluteUri;
                        if (url.IndexOf("AppID") == -1)
                            url = url.Substring(0, url.IndexOf("?") + 1) + "AppID=" + this.Application.Id + "&" + url.Substring(url.IndexOf("?") + 1);
                        script += "window.location.href='" + url + "'";
                    }
                    if (script.Contains("&pf="))
                    {
                        script = script.Substring(0, script.IndexOf("&pf="));
                        script += "'+ '&pf=' + scollvalue";
                    }
                    else
                    {
                        script += "+ '&pf=' + scollvalue";
                    }

                    script += "</script>";


                    this.ibtnCopy.Visible = true;
                    this.ctrlExport.Visible = true;
                }
                else
                {
                    //COD转账
                    //Application app = new Application();
                    //if (this.Application != null)
                    //{
                    //    app.Id = this.AppID;
                    //    app.AppNo = this.Application.AppNo;
                    //    app.IsTransition = this.Application.IsTransition;
                    //    app.DepartmentType = this.Application.DepartmentType;
                    //    app.DepartmentName = this.Application.DepartmentName;
                    //}
                    //if (app.DepartmentType == null && this.Department != "")
                    //{
                    //    app.DepartmentType = utility.GetDicItem(this.Department, BEGDC.CC.BL.Common.DicType.DepartmentType);
                    //    app.IsTransition = this.Transition;
                    //}
                    //if (app.DepartmentName == null && this.Branch != null && this.Branch != "")
                    //{
                    //    app.DepartmentName = new Department();
                    //    app.DepartmentName.Id = Convert.ToInt32(this.Branch);
                    //}

                    //CustomerInfo customer = new CustomerInfo();
                    //BusinessPurpose business = new BusinessPurpose();
                    //Topic topic = new Topic();
                    //SalesTeamInfo salesTeam = new SalesTeamInfo();
                    //LogisticalInfo logist = new LogisticalInfo();
                    //PaymentInfo payment = new PaymentInfo();
                    //IList customerAttendee = new ArrayList();
                    //IList alAttendee = new ArrayList();
                    //IList site = new ArrayList();
                    //IList cost = new ArrayList();
                    //IList contract = new ArrayList();
                    ////update Jovi
                    //DataTable HotelTable = null;
                    //DataTable CompanyCarTable = null;
                    //DataTable LeaseCarTable = null;

                    //EZCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);
                    //app.ApplicationType = WorkflowTypes.CR;
                    //CRService.SaveEZApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, false, true);

                    //this.AppID = app.Id;
                    //this.Application = app;
                    //EZCtrl.CustomerID = customer.Id;
                    //EZCtrl.TopicID = topic.Id;
                    //EZCtrl.SalesTeamID = salesTeam.Id;
                    //EZCtrl.LogistID = logist.Id;
                    //EZCtrl.BusinessID = business.Id;
                    //EZCtrl.PaymentID = payment.Id;

                    //Session["AppID"] = this.Application.Id;

                    //if (url == string.Empty)
                    //    script += "alert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');";
                    //if (url != string.Empty)
                    //{
                    //    if (url.IndexOf("AppID") == -1)
                    //        url = url.Substring(0, url.IndexOf("?") + 1) + "AppID=" + app.Id + "&" + url.Substring(url.IndexOf("?") + 1);
                    //    script += "window.location.href='" + url + "'";
                    //}
                    //else
                    //{
                    //    url = Request.Url.AbsoluteUri;
                    //    if (url.IndexOf("AppID") == -1)
                    //        url = url.Substring(0, url.IndexOf("?") + 1) + "AppID=" + app.Id + "&" + url.Substring(url.IndexOf("?") + 1);
                    //    script += "window.location.href='" + url + "'";
                    //}
                    //script += "</script>";

                    ////Page.RegisterClientScriptBlock("",script);

                    //this.Btn_Copy.Visible = true;
                    //this.ctrlExport.Visible = true;
                }
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');</script>");
            }
            //<--joan 2008/8/22
            if (!this.saveBeforeSubmit)
            {
                Page.RegisterStartupScript("", script);
            }
            //-->end 
        }
        #endregion

        #region Submit
        void SubmitBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.tbOperationFlag1.Text == "Submit")
                {
                    string msg;
                    this.saveBeforeSubmit = true;
                    this.SaveBtn_Click(this.ibtnSave, null);
                    this.saveBeforeSubmit = false;

                    //IList attTypes = new ArrayList();
                    //attTypes.Add(BEGDC.CC.BL.CCFlow.AttachmentType.AGENDA);
                    //attTypes.Add(BEGDC.CC.BL.CCFlow.AttachmentType.BUDGET);
                    //msg = BEGDC.CC.BL.CCFlow.AttachmentService.GetMissedAttachmentMessage( this.AppID, attTypes );
                    msg = BEGDC.CC.BL.CCFlow.AttachmentService.GetMissedAttachmentMessage(this.AppID);

                    if (msg != "" && msg != string.Empty)
                    {
                        Page.RegisterClientScriptBlock("", "<script>alert('" + msg + "')</script>");
                        return;
                    }

                    Implement_Submit();
                    //InValidAllSession();
                }
            }
            catch (Exception exp)
            {
                //InValidAllSession();
                throw exp;
                //Page.RegisterClientScriptBlock("","<script>alert('Submit failed!');</script>");
            }
        }

        private Employee GetUser(string name)
        {
            IUser userService = AppContainer.Instance[ServiceConst.UserService] as IUser;
            return userService.GetUser(name);
        }

        private void Implement_Submit()
        {
            try
            {
                //OBTAIN BASIC INFORMATION
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
                BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

                //Check Validation for CAT VP/PSO Head/Dept Head
                if (!CheckFormValidation())
                {
                    return;
                }

                //BIND FLOW MEMBERS
                IList MemberList = BindFlowMember();

                //if (!this.Transition)
                //{
                App = NormalCtrl.BuildApplication(App);
                if (App.AppNo.IndexOf("-D") > -1)
                    App.AppNo = string.Empty;

                //if(App.DepartmentType==null&&this.Department!="")
                //{
                //	App.DepartmentType = utility.GetDicItem(this.Department,  BEGDC.CC.BL.Common.DicType.DepartmentType);
                //	App.IsTransition = this.Transition;
                //}
                //if(App.DepartmentName==null&&this.Branch!=null&&this.Branch!="")
                //{
                //	App.DepartmentName = new Department();
                //	App.DepartmentName.Id = Convert.ToInt32(this.Branch);
                //}

                BEGDC.CC.Entity.CustomerInfo customerinfo = NormalCtrl.BuildCustomer(App);
                BEGDC.CC.Entity.LogisticalInfo logisticinfo = NormalCtrl.BuildLogistic(App);
                IList VisitingList = NormalCtrl.BuildAppVisiting();

                //OBTAIN SESSION INFORMATION
                DataTable CustomerTable = this.NormalCtrl.CustomerDataTable;
                DataTable AccompanyTable = this.NormalCtrl.ALAttendeeDataTable;
                DataTable HotelTable = this.NormalCtrl.HotelDataTable;
                DataTable CompanyCarTable = this.NormalCtrl.CompanyCarDataTable;
                DataTable LeaseCarTable = this.NormalCtrl.LeaseCarDataTable;

                App.ApplicationType = WorkflowTypes.CR;

                BindAppDepartment(ref App);

                CRService.SubmitNormalApplication(App, customerinfo, logisticinfo, VisitingList, CustomerTable, AccompanyTable, HotelTable, CompanyCarTable, LeaseCarTable, MemberList, string.Empty);
                //}
                //else
                //{
                #region COD转账
                ////COD转账
                //if (this.EZCtrl.IsSomeoneElse && this.EZCtrl.SomeoneEmployee == null)
                //{
                //    Page.RegisterClientScriptBlock("", "<script>alert('Please specify some one else you are delegating for');</script>");
                //    return;
                //}
                //if (this.EZCtrl.IsSomeoneElse && this.EZCtrl.SomeoneEmployee != null)
                //{
                //    BEGDC.CC.Entity.Employee Someone = this.EZCtrl.SomeoneEmployee;
                //    this.Branch = Someone.Department.Id.ToString();
                //    this.Department = Someone.Department.DepartmentType.DicItemKey;
                //}

                //Application app = new Application();
                //if (this.Application != null)
                //{
                //    app.Id = this.AppID;
                //    app.AppNo = this.Application.AppNo;
                //    if (App.AppNo.IndexOf("-D") > -1)
                //        App.AppNo = string.Empty;
                //    app.IsTransition = this.Application.IsTransition;
                //    app.DepartmentType = this.Application.DepartmentType;
                //    app.DepartmentName = this.Application.DepartmentName;
                //}
                ////					if(app.DepartmentType==null&&this.Department!="")
                ////					{
                ////						app.DepartmentType = utility.GetDicItem(this.Department,  BEGDC.CC.BL.Common.DicType.DepartmentType);
                ////						app.IsTransition = this.Transition;
                ////					}
                ////					if(app.DepartmentName==null&&this.Branch!=null&&this.Branch!="")
                ////					{
                ////						app.DepartmentName = new Department();
                ////						app.DepartmentName.Id = Convert.ToInt32(this.Branch);
                ////					}

                //CustomerInfo customer = new CustomerInfo();
                //BusinessPurpose business = new BusinessPurpose();
                //Topic topic = new Topic();
                //SalesTeamInfo salesTeam = new SalesTeamInfo();
                //LogisticalInfo logist = new LogisticalInfo();
                //PaymentInfo payment = new PaymentInfo();
                //IList customerAttendee = new ArrayList();
                //IList alAttendee = new ArrayList();
                //IList site = new ArrayList();
                //IList cost = new ArrayList();
                //IList contract = new ArrayList();
                ////update Jovi
                //DataTable HotelTable = null;
                //DataTable CompanyCarTable = null;
                //DataTable LeaseCarTable = null;

                //EZCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);
                //app.ApplicationType = WorkflowTypes.CR;

                //BindAppDepartment(ref app);

                //CRService.SubmitEZApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, MemberList, string.Empty, true);
                #endregion
                //}

                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                //throw exp;
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
            }
        }

        private void BindAppDepartment(ref BEGDC.CC.Entity.Application app)
        {
            IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
            if (app.SomeoneElseNo != null)
            {
                IUser UserService = AppContainer.Instance[ServiceConst.UserService] as IUser;
                Employee tempe = UserService.GetUserByID(app.SomeoneElseNo.Id);
                app.SomeoneElseNo = tempe;
                app.DepartmentType = utility.GetDicItem(app.SomeoneElseNo.Department.DepartmentType.DicItemKey, BEGDC.CC.BL.Common.DicType.DepartmentType);
                app.IsTransition = this.Transition;
                app.DepartmentName = new Department();
                app.DepartmentName.Id = Convert.ToInt32(app.SomeoneElseNo.Department.Id);
            }
            else
            {
                if (app.DepartmentType == null && this.Department != "")
                {
                    app.DepartmentType = utility.GetDicItem(this.Department, BEGDC.CC.BL.Common.DicType.DepartmentType);
                    app.IsTransition = this.Transition;
                }
                if (app.DepartmentName == null && this.Branch != null && this.Branch != "")
                {
                    app.DepartmentName = new Department();
                    app.DepartmentName.Id = Convert.ToInt32(this.Branch);
                }
            }
        }

        private bool CheckFormValidation()
        {
            IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
            //if (this.Transition)
            //{
            //    if (this.EZCtrl.CustomerNum == 0)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('At least one customer should be specified.');</script>");
            //        return false;
            //    }
            //    if (this.EZCtrl.AccompanyNum == 0)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('At least one Alcatel-Lucent attendee should be specified.');</script>");
            //        return false;
            //    }
            //    if (this.EZCtrl.HotelNum == 0)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('At least one Hotel should be specified.');</script>");
            //        return false;
            //    }
            //    if (this.EZCtrl.CostCenterNum == 0)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('At least one cost center code should be specified.');</script>");
            //        return false;
            //    }
            //}
            //else
            //{
            if (this.NormalCtrl.CustomerNum == 0)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('At least one customer should be specified. 至少有一个客户参与!');</script>");
                return false;
            }
            //				if(this.NormalCtrl.AccompanyNum==0)
            //				{
            //					Page.RegisterClientScriptBlock("","<script>alert('At least one Alcatel-Lucent attendee should be specified.');</script>");
            //					return false;
            //				}
            //}

            //Employee emp = this.GetUser(HttpContext.Current.User.Identity.Name);
            //if (this.Transition && this.EZCtrl.IsSomeoneElse && this.EZCtrl.SomeoneEmployee != null)
            //{
            //    emp = this.EZCtrl.SomeoneEmployee;
            //}

            //Comment out by leoren at 4.13

            //DataTable dataTable = null;
            //if (emp.Department.DepartmentType.DicItemKey == BEGDC.CC.BL.Common.SysDicItem.DepartmentType.CAT)
            //{
            //    dataTable = utility.GetRoleMemberList(BEGDC.CC.BL.Workflow.UserRole.CATVP, emp.Department.Id.ToString());
            //    if (dataTable == null || dataTable.Rows.Count == 0)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('No CAT VP available. CAT VP 不可用!');</script>");
            //        return false;
            //    }
            //    else if (dataTable.Rows.Count > 1)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('There are more than one CAT VP. 多个CAT VP!');</script>");
            //        return false;
            //    }
            //}
            //else if (emp.Department.DepartmentType.DicItemKey == BEGDC.CC.BL.Common.SysDicItem.DepartmentType.OtherDepartment)
            //{
            //    dataTable = utility.GetRoleMemberList(BEGDC.CC.BL.Workflow.UserRole.DeptHead, emp.Department.Id.ToString());
            //    if (dataTable == null || dataTable.Rows.Count == 0)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('No Department Head available. 部门主管不可用!');</script>");
            //        return false;
            //    }
            //    else if (dataTable.Rows.Count > 1)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('There are more than one Department Head.多个部门主管!');</script>");
            //        return false;
            //    }

            //    dataTable = utility.GetDepartmentFNC(emp.Department.Id.ToString());
            //    if (dataTable == null || dataTable.Rows.Count == 0)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('No FNC available. FNC不可用!');</script>");
            //        return false;
            //    }
            //    else if (dataTable.Rows.Count > 1)
            //    {
            //        Page.RegisterClientScriptBlock("", "<script>alert('There are more than one FNC. 多个FNC!');</script>");
            //        return false;
            //    }
            //}
            return true;
        }
        #endregion

        #region Copy
        void CopyBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                CRService.CopyCR(this.AppID);
            }
            catch (Exception exp)
            {
                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR002 + "');window.close();</script>");
                //throw exp;
            }
            Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CM004 + "');</script>");

            this.ibtnCopy.Visible = true;
            this.ctrlExport.Visible = true;
            //			try
            //			{
            //				//OBTAIN BASIC INFORMATION
            //				ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
            //				IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
            //				//BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);
            //				BEGDC.CC.Entity.Application App = null;
            //
            //				if(!this.Transition)
            //				{
            //					App = NormalCtrl.BuildApplication(App);
            //					if(App.DepartmentType==null&&this.Department!="")
            //					{
            //						App.DepartmentType = utility.GetDicItem(this.Department,  BEGDC.CC.BL.Common.DicType.DepartmentType);
            //						App.IsTransition = this.Transition;
            //					}
            //					if(App.DepartmentName==null&&this.Branch!=null&&this.Branch!="")
            //					{
            //						App.DepartmentName = new Department();
            //						App.DepartmentName.Id = Convert.ToInt32(this.Branch);
            //						//App.DepartmentName = utility.GetDicItem(this.Branch,this.Department);
            //						//App.DepartmentName = utility.GetDicItem(Convert.ToInt32(this.Branch));
            //					}
            //
            //					BEGDC.CC.Entity.CustomerInfo customerinfo = NormalCtrl.BuildCustomer(App);
            //					BEGDC.CC.Entity.LogisticalInfo logisticinfo = NormalCtrl.BuildLogistic(App);
            //					IList VisitingList = NormalCtrl.BuildAppVisiting();
            //
            //					//OBTAIN SESSION INFORMATION
            //					DataTable CustomerTable = this.NormalCtrl.CustomerDataTable;
            //					DataTable AccompanyTable = this.NormalCtrl.ALAttendeeDataTable;
            //					DataTable HotelTable = this.NormalCtrl.HotelDataTable;
            //					DataTable CompanyCarTable = this.NormalCtrl.CompanyCarDataTable;
            //					DataTable LeaseCarTable = this.NormalCtrl.LeaseCarDataTable;
            //
            //					//Copy Operation
            //					//App.Id = 0;
            //					//customerinfo.Id=0;
            //					//logisticinfo.Id = 0;
            //					CustomerTable = this.InitializeDataTable(CustomerTable);
            //					AccompanyTable = this.InitializeDataTable(AccompanyTable);
            //					HotelTable = this.InitializeDataTable(HotelTable);
            //					CompanyCarTable = this.InitializeDataTable(CompanyCarTable);
            //					LeaseCarTable = this.InitializeDataTable(LeaseCarTable);
            //					App.ApplicationType = WorkflowTypes.CR;
            //					CRService.SaveNormalApplication(App,customerinfo,logisticinfo,VisitingList, CustomerTable,AccompanyTable,HotelTable,CompanyCarTable,LeaseCarTable, true);
            //
            //					Page.RegisterClientScriptBlock("","<script>alert('Copy successfully.');</script>");
            //
            //					//this.AppID = App.Id;
            //					//this.Application = App;
            //					//this.tx_AppState.Text = "Copy of  "+ App.AppNo;
            //					//this.tx_AppState.Visible = true;
            //				}
            //				else
            //				{
            //					Application app = new Application();
            //					if(this.Application!=null)
            //					{
            //						app.IsTransition = this.Application.IsTransition;
            //						app.DepartmentType = this.Application.DepartmentType;
            //						app.DepartmentName = this.Application.DepartmentName;
            //					}
            //					if(app.DepartmentType==null&&this.Department!="")
            //					{
            //						app.DepartmentType = utility.GetDicItem(this.Department,  BEGDC.CC.BL.Common.DicType.DepartmentType);
            //						app.IsTransition = this.Transition;
            //					}
            //					if(app.DepartmentName==null&&this.Branch!=null&&this.Branch!="")
            //					{
            //						app.DepartmentName = new Department();
            //						app.DepartmentName.Id = Convert.ToInt32(this.Branch);
            //					}
            //
            //					CustomerInfo customer = new CustomerInfo();
            //					BusinessPurpose business = new BusinessPurpose();
            //					Topic topic = new Topic();
            //					SalesTeamInfo salesTeam = new SalesTeamInfo();
            //					LogisticalInfo logist = new LogisticalInfo();
            //					PaymentInfo payment = new PaymentInfo();
            //					IList customerAttendee = new ArrayList();
            //					IList alAttendee = new ArrayList();
            //					IList site = new ArrayList();
            //					IList cost = new ArrayList();
            //					IList contract = new ArrayList();
            //					//update Jovi
            //					DataTable HotelTable = null;
            //					DataTable CompanyCarTable = null;
            //					DataTable LeaseCarTable = null;
            //
            //					EZCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);
            //					app.ApplicationType = WorkflowTypes.CR;
            //					CRService.SaveEZApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost,contract,HotelTable, CompanyCarTable, LeaseCarTable, true, true);
            //
            //					//Page.RegisterClientScriptBlock("","<script>alert('Copy successfully.');</script>");
            //					Page.RegisterClientScriptBlock("","<script>alert('" + BEGDC.CC.Resource.SystemMessage.CV001 + "');</script>");
            //
            ////					this.AppID = app.Id;
            ////					this.Application = app;
            ////					this.tx_AppState.Text = "Copy of  "+ app.AppNo;
            ////					this.tx_AppState.Visible = true;
            //				}
            //			}
            //			catch(Exception exp)
            //			{
            //				throw exp;
            //			}
        }

        private DataTable InitializeDataTable(System.Data.DataTable dataTable)
        {
            DataRow dataRow;
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                dataRow = dataTable.Rows[i];
                dataRow[0] = 0;
            }
            return dataTable;
        }
        #endregion

        #region ButtonStatusSetting
        protected override void ButtonStatusSetting()
        {
            if (this.Access == null)
                return;

            this.ibtnSubmit.Visible = this.Access.IsButtonVisible(CRTransitionList.Submit);
            this.ibtnSave.Visible = this.Access.IsButtonVisible(CRTransitionList.Save);
            this.ibtnReply.Visible = this.Access.IsButtonVisible(CRTransitionList.Reply);
            this.ibtnCopy.Visible = this.Access.IsButtonVisible(CRTransitionList.Copy);

            if (((this.Access.IsHideAllButton || this.Access.IsReadOnly) || (this.Step != WorkTransition.Draft
                && this.Step != WorkTransition.CR_Request && this.Step != WorkTransition.CR_ReRequest)) && !this.IsQuery)
                TR_title.Visible = false;

            if ((this.Access.IsReadOnly || this.IsView))
                isReadOnly = true;
        }
        #endregion

        #region Reply
        void ReplyBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ICR CRService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
                BEGDC.CC.Entity.Application App = CRService.GetApplication(this.AppID);

                if (!App.IsTransition)
                {
                    App = NormalCtrl.BuildApplication(App);
                    if (App.DepartmentType == null && this.Department != "")
                    {
                        App.DepartmentType = utility.GetDicItem(this.Department, BEGDC.CC.BL.Common.DicType.DepartmentType);
                        App.IsTransition = this.Transition;
                    }
                    if (App.DepartmentName == null && this.Branch != null && this.Branch != "")
                    {
                        App.DepartmentName = new Department();
                        App.DepartmentName.Id = Convert.ToInt32(this.Branch);
                    }

                    BEGDC.CC.Entity.CustomerInfo customerinfo = NormalCtrl.BuildCustomer(App);
                    BEGDC.CC.Entity.LogisticalInfo logisticinfo = NormalCtrl.BuildLogistic(App);
                    IList VisitingList = NormalCtrl.BuildAppVisiting();

                    //OBTAIN SESSION INFORMATION
                    DataTable CustomerTable = this.NormalCtrl.CustomerDataTable;
                    DataTable AccompanyTable = this.NormalCtrl.ALAttendeeDataTable;
                    DataTable HotelTable = this.NormalCtrl.HotelDataTable;
                    DataTable CompanyCarTable = this.NormalCtrl.CompanyCarDataTable;
                    DataTable LeaseCarTable = this.NormalCtrl.LeaseCarDataTable;

                    App.ApplicationType = WorkflowTypes.CR;
                    CRService.SaveNormalApplication(App, customerinfo, logisticinfo, VisitingList, CustomerTable, AccompanyTable, HotelTable, CompanyCarTable, LeaseCarTable, false);
                }
                //COD转账
                //else
                //{
                //    Application app = new Application();
                //    if (this.Application != null)
                //    {
                //        app.Id = this.AppID;
                //        app.AppNo = this.Application.AppNo;
                //        app.IsTransition = this.Application.IsTransition;
                //        app.DepartmentType = this.Application.DepartmentType;
                //        app.DepartmentName = this.Application.DepartmentName;
                //    }
                //    if (app.DepartmentType == null && this.Department != "")
                //    {
                //        app.DepartmentType = utility.GetDicItem(this.Department, BEGDC.CC.BL.Common.DicType.DepartmentType);
                //        app.IsTransition = this.Transition;
                //    }
                //    if (app.DepartmentName == null && this.Branch != null && this.Branch != "")
                //    {
                //        app.DepartmentName = new Department();
                //        app.DepartmentName.Id = Convert.ToInt32(this.Branch);
                //    }

                //    CustomerInfo customer = new CustomerInfo();
                //    BusinessPurpose business = new BusinessPurpose();
                //    Topic topic = new Topic();
                //    SalesTeamInfo salesTeam = new SalesTeamInfo();
                //    LogisticalInfo logist = new LogisticalInfo();
                //    PaymentInfo payment = new PaymentInfo();
                //    IList customerAttendee = new ArrayList();
                //    IList alAttendee = new ArrayList();
                //    IList site = new ArrayList();
                //    IList cost = new ArrayList();
                //    IList contract = new ArrayList();
                //    //update Jovi
                //    DataTable HotelTable = null;
                //    DataTable CompanyCarTable = null;
                //    DataTable LeaseCarTable = null;

                //    EZCtrl.BuildApplication(ref app, ref customer, ref business, ref topic, ref salesTeam, ref logist, ref payment, ref customerAttendee, ref alAttendee, ref site, ref cost, ref contract, ref HotelTable, ref CompanyCarTable, ref LeaseCarTable);
                //    app.ApplicationType = WorkflowTypes.CR;
                //    CRService.SaveEZApplication(app, customer, business, topic, salesTeam, logist, payment, customerAttendee, alAttendee, site, cost, contract, HotelTable, CompanyCarTable, LeaseCarTable, false, true);
                //}

                CRService.ReplyQuery(Convert.ToInt64(Request.QueryString["FlowID"]), WebUtility.DeCodeString(Server, tbComment.Text));

                Page.RegisterClientScriptBlock("", "<script>alert('" + BEGDC.CC.Resource.SystemMessage.CR001 + "');window.close();</script>");
            }
            catch (Exception exp)
            {
                throw exp;
                //Page.RegisterClientScriptBlock("","<script>alert('Submit failed!');</script>");
            }
        }
        #endregion
    }
}
